package com.m3958.firstgwt.server.dao;

import java.io.File;
import java.util.List;

import javax.servlet.ServletContext;

import com.m3958.firstgwt.client.types.ServerErrorCode;
import com.m3958.firstgwt.server.model.Link;
import com.m3958.firstgwt.server.model.Section;
import com.m3958.firstgwt.server.model.WebHost;
import com.m3958.firstgwt.server.model.WebSite;
import com.m3958.firstgwt.server.service.FilePathService;
import com.m3958.firstgwt.server.service.SiteConfiger.SiteConfigerKeyName;
import com.m3958.firstgwt.server.types.SmartError;

public class WebSiteChangeStrategy extends BaseModelChangeStrategy implements ModelChangeStrategy<WebSite> {
	
	private void setImgSizes(WebSite ws){
		if(ws.getImgSizes() == null || ws.getImgSizes().isEmpty()){
			ws.setImgSizes("48x48");
		}
		if(ws.getImgSizes().indexOf("48x48") == -1){
			ws.setImgSizes(ws.getImgSizes() + ",48x48");
		}
		if(ws.getTplTech() == null || ws.getTplTech().isEmpty()){
			ws.setTplTech("ftl");
		}
	}

	@Override
	public boolean extraPersistTask(WebSite model){
		if(model.getArticleFlags() != null && !model.getArticleFlags().isEmpty()){
			model.setArticleFlags(model.getArticleFlags().replaceAll("，", ","));
		}
		
		setImgSizes(model);
		model.setImgSizes(model.getImgSizes().replaceAll("，", ","));
		model.setServicePeroid(365);
		model.setUnitPrice(0);
		model.setOutOfService(false);
		createPerRoleAsignToUser(model);
		return true;
	}

	private void createSiteDir(WebSite model) {
		String s = siteConfiger.getValue(SiteConfigerKeyName.SITE_ROOT);
		File f = new File(s,model.getId()+"");
		if(!f.exists()){
			f.mkdirs();
		}
	}
	
	@Override
	public boolean extraRemoveTask(WebSite model) {
		String s = siteConfiger.getValue(SiteConfigerKeyName.SITE_ROOT);
		
		File[] fs;
		File f;
		try {
			f = new File(s,model.getId()+"");
			fs = f.listFiles();
		} catch (Exception e) {
			return true;
		}
		if(f.exists()){
			if(fs == null){
				f.delete();
				return true;
			}
		}else{
			return true;
		}
		
		if(fs.length > 0){
			getErrors().addError(new SmartError("請先清空站點目錄！", ServerErrorCode.DEPENDENCY_ERROR));
			return false;
		}
		if(model.getWebhosts().size() > 0){
			getErrors().addError(new SmartError("請先删除对应的主机名！", ServerErrorCode.DEPENDENCY_ERROR));
			return false;
		}
		
		SectionDao sdao = injector.getInstance(SectionDao.class);
		List<Section> ss = sdao.getTopSections(model.getId());
		if(ss.size() > 0){
			getErrors().addError(new SmartError("請先删除站点的文章目录！", ServerErrorCode.DEPENDENCY_ERROR));
			return false;
		}
		
		LinkDao ldao = injector.getInstance(LinkDao.class);
		List<Link> lcs = ldao.getTopLinks(model.getId());
		
		if(lcs.size() > 0){
			getErrors().addError(new SmartError("請先删除站点的链接条目！", ServerErrorCode.DEPENDENCY_ERROR));
			return false;
		}
		
		if(f.exists())f.delete();
		return true;
	}

	@Override
	public boolean extraUpdateTask(WebSite model,WebSite newModel){
		setImgSizes(newModel);
		if(!getSu().isSuperman()){
			newModel.setUnitPrice(model.getUnitPrice());
			newModel.setServicePeroid(model.getServicePeroid());
			newModel.setOutOfService(model.isOutOfService());
			newModel.setServiceEndDate(model.getServiceEndDate());
		}
		return true;
	}

	@Override
	public boolean afterPersist(WebSite model) {
		createSiteDir(model);
		WebHost wh = new WebHost();
		wh.setWebSite(model);
		wh.setName(model.getEname() + "." + getScs().getAppDomain());
		wh.setTheme("default");
		wh.setAudit(true);
		model.getWebhosts().add(wh);
		
		File f = new File(siteConfiger.getValue(SiteConfigerKeyName.SITE_ROOT),model.getId()+"");
		f = new File(f,wh.getTheme());
		if(!f.exists()){
			f.mkdir();
			FilePathService fps = injector.getInstance(FilePathService.class);
			ServletContext sc = injector.getInstance(ServletContext.class);
			if("vm".equals(model.getTplTech())){
				File indexftl = new File(sc.getRealPath("/"),"indexvm.vm");
				fps.copyFile(indexftl, new File(f,"index.vm"));
			}else{
				File indexftl = new File(sc.getRealPath("/"),"indexftl.ftl");
				fps.copyFile(indexftl, new File(f,"index.ftl"));
			}
		}
		
		SectionDao sdao = injector.getInstance(SectionDao.class);
		Section s = new Section();
		s.setName(model.getCname() + "文章目录");
		s.setSiteId(model.getId());
		sdao.smartPersistBaseModel(s);
		return true;
	}
}
